﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Cosmetic.Logic;
using System.Configuration;
using Cosmetic.DataEntity;
using System.Collections;
using Cosmetic;

namespace WebApp.Product
{
    public partial class ProductInfor_rh : PageBase
    {
        public float TotalTags { get; set; }
        public float TotalComments { get; set; }

        private ProductManager m_ProductManager = new ProductManager();
        private CommentManager m_CommentManager = new CommentManager();
        private TagManager m_TagManager = new TagManager();
        private UserManager m_UserManager = new UserManager();
        private CategoryManager m_CategoryManager = new CategoryManager();
        private SaleManager m_salemanager = new SaleManager();
        private PlateManager PM = new PlateManager();
        private DiscountProductManagement discountPM = new DiscountProductManagement();

        string NotifyAddress = ConfigurationManager.AppSettings["NotifyAddress"];
        string ReturnAddress = ConfigurationManager.AppSettings["ReturnAddress"];

        Cosmetic.DataEntity.Product m_Product;
        Cosmetic.DataEntity.Product m_ProductInfo;

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!string.IsNullOrEmpty(Request.QueryString["PID"]))
            {
                string a = this.Request.QueryString["PID"];
                Session["pid"] = this.Request.QueryString["PID"];
                //this.m_Product = this.m_ProductManager.GetProductById1(new Guid(a));
                this.m_Product = this.m_ProductManager.GetProductByUID(a);
                this.m_ProductInfo = this.m_ProductManager.GetProductByUID(a);
                //this.m_ProductInfo = this.m_ProductManager.GetProductInfoById_Con(new Guid(a));
            }
            else
            {
                string b = Session["pid"].ToString();
                //this.m_Product = this.m_ProductManager.GetProductById1(new Guid(b));
                this.m_Product = this.m_ProductManager.GetProductByUID(b);
                this.m_ProductInfo = this.m_ProductManager.GetProductByUID(b);
                //this.m_ProductInfo = this.m_ProductManager.GetProductInfoById_Con(new Guid(b));
            }

            string CategoryId = "";
            string secondCategoryId = "";
            string topCategoryId = "";
            string topCategoryName = "";
            string CategoryName = "";
            string secondCategoryName = "";

            if (m_Product.ProductCategory.CategoryId != null)
            {
                CategoryId = m_Product.ProductCategory.CategoryId.ToString();
                CategoryName = m_Product.ProductCategory.Name;
                if (m_Product.ProductCategory.SupCategory != null)
                {
                    secondCategoryId = m_Product.ProductCategory.SupCategory.CategoryId.ToString();
                    secondCategoryName = m_Product.ProductCategory.SupCategory.Name;

                    if (m_Product.ProductCategory.SupCategory.SupCategory != null)
                    {
                        topCategoryId = m_Product.ProductCategory.SupCategory.SupCategory.CategoryId.ToString();
                        topCategoryName = m_Product.ProductCategory.SupCategory.SupCategory.Name;
                    }
                }
            }

            //m_Product.ProductCategory.SupCategory.CategoryId.ToString();



            if (CategoryId != "" && secondCategoryId != "" && topCategoryId != "")
            {
                this.HLThirdCategory.Text = CategoryName;
                this.HLThirdCategory.NavigateUrl = "~/Product/ProductCategory.aspx?CID=" + secondCategoryId + "&SID=" + CategoryId;

                this.HLSeconeCategory.Text = secondCategoryName;
                this.HLSeconeCategory.NavigateUrl = "~/Product/ProductCategory.aspx?CID=" + secondCategoryId;

                this.HLTopCategory.Text = topCategoryName;
                this.HLTopCategory.NavigateUrl = "~/Product/ProductTopCategory.aspx?CID=" + topCategoryId;
            }
            else
            {
                this.HLThirdCategory.Text = "无";
                //this.HLThirdCategory.NavigateUrl = "~/Product/ProductCategory.aspx?CID=" + secondCategoryId + "&SID=" + CategoryId;

                this.HLSeconeCategory.Text = "无";
                //this.HLSeconeCategory.NavigateUrl = "~/Product/ProductCategory.aspx?CID=" + secondCategoryId;

                this.HLTopCategory.Text = "无";
                //this.HLTopCategory.NavigateUrl = "~/Product/ProductTopCategory.aspx?CID=" + topCategoryId;
            }



            //this.Literal2.Text = m_Product.Name;
            this.img.Src = m_ProductInfo.RecommendPicture1;
            this.LtName.Text = m_Product.Name;
            this.Literal2.Text = m_ProductInfo.ProductCode;
            this.Literal1.Text = m_ProductInfo.Name;

            //this.Page.Title = string.Format("【{0}】价格,{1}什么牌子好_{1}哪里买?首选日花商城!",m_Product.Name,m_Product.ProductCategory.Name);
            this.Page.Title = string.Format("{0}【价格-参数-正品】", m_Product.Name);
            //this.Page.MetaKeywords = string.Format("{0}价格,{0}评价,{1},日花商城",m_Product.Name,m_Product.ProductCategory.Name);
            this.Page.MetaKeywords = string.Format("{0},{0}价格", m_Product.Name);

            //this.Page.MetaDescription = string.Format("{0}价格,{1}哪种好?{0}质量怎么样?日花商城全知道,网购{1},就上日花商城【直销,便捷,诚信！】",m_Product.Name,m_Product.ProductCategory.Name);
            this.Page.MetaDescription = string.Format("日花商城提供{0}的最新报价及使用说明， {1}", m_Product.Name, m_Product.Description);


            if (m_ProductInfo.eprice == Convert.ToDecimal(0.01))
            {
                ImageButton1.Visible = false;
                AskPrice.Visible = true;
                this.Literal4.Text = "询价";
                btnAddCart.Enabled = false;
                ImageButton2.Visible = false;
                this.divBind.Attributes.Add("style", "display:none");
            }
            else
            {
                AskPrice.Visible = false;
                btnAddCart.Enabled = true;
                // Literal4ask.Attributes.Add("style", "display:none");
                this.Literal4.Text = "￥" + Convert.ToString(m_ProductInfo.eprice);
            }
            this.Literal3.Text = Convert.ToString(m_ProductInfo.Price);
            this.LiteralCommon2.Text = m_ProductInfo.Description;
            //this.LabelCountAll.Text = Convert.ToString(m_ProductInfo.网络零售价);
            // this.Literal6.Text = m_ProductInfo.Name;

            BindComment(m_Product, false);
            this.ListView5.DataSource = PM.Getxinpinpro();//新品
            this.ListView5.DataBind();
            if (!IsPostBack)
            {
                this.rptSuiXinPei.DataSource = discountPM.GetDiscountProducts();
                this.rptSuiXinPei.DataBind();
            }
        }

        /// <summary>
        /// 问题咨询。
        /// </summary>
        /// <param name="aProduct"></param>
        private void BindComment(Cosmetic.DataEntity.Product aProduct, bool isAll)
        {

            List<Comment> listComment = null;

            listComment = this.m_CommentManager.GetAllCommentByProduct(aProduct);//GetCommentByProduct(aProduct, 3);

            this.labAllComment.Text = listComment.Count.ToString();//显示总的评论数。
            this.Literal5.Text = listComment.Count.ToString();// "全部咨询"按钮
            txtCommonNum.Text = listComment.Count.ToString();
            if (listComment.Count == 0)
            {
                //  LabelCommentbyUsers.Text = "暂时还没有用户评论。";
            }
            else
            {
                //  LabelCommentbyUsers.Text = "目前已有" + listComment.Count.ToString() + "名用户对该商品进行了评论。";
            }
            if ((listComment.Count % 3) == 0)
            {
                // LabelCountPager.Text = Convert.ToInt32((listComment.Count / 3)).ToString();
            }
            else
            {
                // LabelCountPager.Text = Convert.ToInt32((listComment.Count / 3) + 1).ToString();
            }
            if (isAll)
            {
                this.lvCommend.DataSource = listComment; //显示评论内容。
                this.lvCommend.DataBind();
            }
            else
            {
                this.lvCommend.DataSource = listComment.Take(5).ToList(); //显示评论内容。
                this.lvCommend.DataBind();
            }
        }

        //加入购物车
        protected void ImageButton1_Click(object sender, ImageClickEventArgs e)
        {
            Buy();
            if (Session["buycarts"] != null)
            {

                Page.RegisterStartupScript("openconfirm ", " <script> if(confirm( '尊敬的用户，由于您选择的产品属于不同\\n的支付系统，所以您的购物车内原有的商\\n品会自动取消,是否继续操作？ ')){self.location='../Shopping/shopCart.htm'} else{self.location='../Shopping/shopCarts.htm'} </script> ");

                return;
            }
            else
            {
                Response.Redirect("~/Shopping/shopCart.aspx");
            }
        }

        private void Buy()
        {
            try
            {
                int theCount = Convert.ToInt32(this.txtQuantity.Text.Trim());

                //add to buy cart
                if (null == Session["buycart"])
                {
                    Session["buycart"] = new Hashtable();
                }
                //加入尺寸
                if (null == Session["size"])
                {
                    Session["size"] = new Hashtable();
                }
                try
                {
                    if (((Hashtable)Session["buycart"]).Contains(m_Product.ProductId.ToString()))
                    {
                        int tint = int.Parse(((Hashtable)Session["buycart"])[m_Product.ProductId.ToString()].ToString());
                        ((Hashtable)Session["buycart"])[m_Product.ProductId.ToString()] = (++tint).ToString();

                    }
                    else
                    {
                        ((Hashtable)Session["buycart"]).Add(m_Product.ProductId.ToString(), theCount.ToString());

                    }
                    //Response.Redirect("~/Shopping/shopCart.htm");
                }
                catch (Exception)
                {
                    WebGeneric.WebMessageBox("购物篮添加失败!", this.Page);
                }

            }
            catch
            {
                WebGeneric.WebMessageBox("请正确填写购买数量!", this.Page);
            }

        }

        /// <summary>
        /// 捆绑商品
        /// </summary>
        private void BuyDiscount()
        {
            try
            {
                int theCount = 1; //Convert.ToInt32(this.txtQuantity.Text.Trim());

                //add to buy cart
                if (null == Session["buycart"])
                {
                    Session["buycart"] = new Hashtable();
                }
                //加入尺寸
                if (null == Session["size"])
                {
                    Session["size"] = new Hashtable();
                }
                try
                {
                    if (((Hashtable)Session["buycart"]).Contains(m_Product.ProductId.ToString()))
                    {
                        int tint = int.Parse(((Hashtable)Session["buycart"])[m_Product.ProductId.ToString()].ToString());
                        ((Hashtable)Session["buycart"])[m_Product.ProductId.ToString()] = (++tint).ToString();

                    }
                    else
                    {
                        ((Hashtable)Session["buycart"]).Add(m_Product.ProductId.ToString(), theCount.ToString());

                    }
                    //Response.Redirect("~/Shopping/shopCart.htm");
                }
                catch (Exception)
                {
                    WebGeneric.WebMessageBox("购物篮添加失败!", this.Page);
                }

            }
            catch
            {
                WebGeneric.WebMessageBox("请正确填写购买数量!", this.Page);
            }

        }

        protected void ImageButton2_Click(object sender, ImageClickEventArgs e)
        {
            if (null == this.SignInUser)
            {
                this.Response.Redirect(String.Format("~/Login.htm", this.Request.Url.PathAndQuery));
            }
            if (this.m_UserManager.GetFavoriteById(this.SignInUser.UserId, this.m_Product.ProductId) == null)
            {
                Favorite theFavorite = new Favorite();
                theFavorite.CreateTime = DateTime.Now;
                theFavorite.FavoriteId = Guid.NewGuid();
                theFavorite.ProductId = this.m_Product.ProductId;
                theFavorite.IsFavorite = true;
                theFavorite.UserId = this.SignInUser.UserId;

                this.m_UserManager.AddFavorite(theFavorite);
            }
            Page.RegisterStartupScript("openalert", "<script>alert('收藏成功！');</script>");
            return;
        }

        //我要咨询
        protected void LinkButton1_Click(object sender, EventArgs e)
        {
            Response.Redirect("ProductInfo_rh2_" + Session["pid"].ToString()+".htm");
        }

        protected void LinkButton2_Click(object sender, EventArgs e)
        {
            BindComment(m_Product, true);
        }

        protected void LinkButton3_Click(object sender, EventArgs e)
        {
            BindComment(m_Product, true);
        }

        protected void cbItem_CheckedChanged(object sender, EventArgs e)
        {
            int count = 1;
            int.TryParse(txtQuantity.Text, out count);
            if (count == 0) return;
            Session["DiscountCart"] = null;
            Hashtable dc = new Hashtable();
            decimal DiscountPrices = 0;
            decimal ePrices = 0;
            for (int i = 0; i < this.rptSuiXinPei.Items.Count; i++)
            {
                CheckBox cbox = (CheckBox)rptSuiXinPei.Items[i].FindControl("cbItem");
                HiddenField hfProductId = rptSuiXinPei.Items[i].FindControl("hfProductId") as HiddenField;
                Label lbdiscountPrice = rptSuiXinPei.Items[i].FindControl("lbDiscountPrice") as Label;
                Label lbEPrice = rptSuiXinPei.Items[i].FindControl("lbDisEPrice") as Label;

                //清除折扣车
                if (cbox.Checked == true)
                {//折扣车添加该商品
                    dc.Add(hfProductId.Value, 1);
                    DiscountPrices += decimal.Parse(lbdiscountPrice.Text);
                    ePrices += decimal.Parse(lbEPrice.Text);
                }
            }


            this.ltlDiscountCount.Text = dc.Count.ToString();
            if (this.ltlDiscountCount.Text == "0" || string.IsNullOrEmpty(ltlDiscountCount.Text))
            {
                ltlDiscountPrices.Text = "0";
                ltlDisEPrice.Text = "0";
                Session["DiscountCart"] = null;
            }
            else
            {
                ltlDiscountPrices.Text = (DiscountPrices + m_ProductInfo.eprice * count).ToString();
                ltlDisEPrice.Text = (ePrices - DiscountPrices).ToString();
                Session["DiscountCart"] = dc;
            }
        }

        protected void btnAddCart_Click(object sender, EventArgs e)
        {
            Buy();
            if (Session["buycarts"] != null)
            {
                Page.RegisterStartupScript("openconfirm ", " <script> if(confirm( '尊敬的用户，由于您选择的产品属于不同\\n的支付系统，所以您的购物车内原有的商\\n品会自动取消,是否继续操作？ ')){self.location='../Shopping/shopCart.htm'} else{self.location='../Shopping/shopCarts.htm'} </script> ");
                return;
            }
            else
            {
                Response.Redirect("~/Shopping/shopCart.aspx");
            }
        }

        protected void LinkButton4_Click(object sender, EventArgs e)
        {
            Session["DiscountCart"] = null;
            ltlDiscountCount.Text = "0";
            ltlDiscountPrices.Text = "0";
            ltlDisEPrice.Text = "0";
        }

    }//end class
}